<?php
namespace app\api\model;
use think\Model;
class UserCountry extends Model
{

    /**
     * @param $country_ids
     * @param $user_id
     * 存国家
     */
    public function add($country_ids,$user_id){
        foreach ($country_ids as $k=>$v){
            $addData = array(
                'country_id'=>$v,
                'user_id'=>$user_id,
            );
            $this->insertGetId($addData);
        }
    }

    /**
     * @param $country_ids
     * @param $user_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 修改国家
     */
    public function edit($country_ids,$user_id){
        //首先全部改为0
        $this->where(array('user_id'=>$user_id))->update(array('status'=>0));
        foreach ($country_ids as $k=>$v){
            //查询有没有
            $info = $this->where(array('user_id'=>$user_id,'country_id'=>$v))->find();
            if($info){
                $this->where(array('user_id'=>$user_id,'country_id'=>$v))->update(array('status'=>1));
            }else {
                $addData = array(
                    'country_id' => $v,
                    'user_id' => $user_id,
                );
                $this->insertGetId($addData);
            }
        }
    }

    /**
     * @param $user_id
     * @return array
     * 通过国家id获取用户id
     */
    public function get_user_id($user_id){

        $country_ids = $this->where(array('user_id'=>$user_id,'status'=>1))->column('country_id');
        return $country_ids;
    }

    /**
     * @param $country_ids
     * @return array
     * 通过用户id获取国家id
     */
    public function getCountryIds($country_ids){

        $user_ids = $this->where(array('country_id'=>array('in',$country_ids),'status'=>1))->column('user_id');
        return $user_ids;
    }

}